package org.wedding.center.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.wedding.system.entity.UserInfo;
import org.wedding.system.service.IUserService;
import org.wedding.center.entity.AmountInfo;
import org.wedding.center.entity.ApprovalInfo;
import org.wedding.center.entity.RightInfo;
import org.wedding.center.mapper.AmountInfoMapper;
import org.wedding.center.service.AmountInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.wedding.enums.system.ResultCodeEnum;
import org.wedding.utils.CommonResult;
import org.wedding.center.service.ApprovalInfoService;
import org.wedding.center.service.RightInfoService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.stereotype.Service;
import cn.hutool.core.util.ObjectUtil;
import org.wedding.dto.PageModel;
import org.wedding.utils.PageUtil;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 金额明细表(AmountInfo)表服务实现类
 *
 * @author songkaiyue
 * @since 2025-05-19 17:26:20
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AmountInfoServiceImpl extends ServiceImpl<AmountInfoMapper, AmountInfo> implements AmountInfoService {
    @Resource
    private ApprovalInfoService approvalInfoService;
    @Resource
    private IUserService userService;
    @Resource
    private RightInfoService rightInfoService;

    /**
     * 分页查询所有数据
     *
     * @return
     */
    @Override
    public CommonResult<PageModel> findAll(PageModel query, String changeType, String changeTypes) {
        try {
            List<AmountInfo> list = baseMapper.selectAll(changeType,changeTypes);
            List<AmountInfo> setList = query.setList(PageUtil.getListPage(query.getCurrent(), query.getPageSize(), list), list.size());
            if (!setList.isEmpty()) {
                for (AmountInfo amountInfo : setList) {
                    UserInfo userInfo = userService.view(amountInfo.getUserId()).getData();
                    if (ObjectUtil.isNotEmpty(userInfo)) {
                        if (StrUtil.isEmpty(amountInfo.getPayBank())) {
                            amountInfo.setPayBank(userInfo.getPayBank());
                        }
                        if (StrUtil.isEmpty(amountInfo.getPayCode())) {
                            amountInfo.setPayCode(userInfo.getPayCode());
                        }
                        if (StrUtil.isEmpty(amountInfo.getPayName())) {
                            amountInfo.setPayName(userInfo.getPayName());
                        }
                    }
                }
            }
            query.setList(setList, list.size());
            return CommonResult.success(query);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }
    /**
     * 分页查询所有数据
     *
     * @return
     */
    @Override
    public CommonResult<PageModel> findAllaa(PageModel query, String changeType, String changeTypes) {

        try {
            //0:普通用户  1: 商家  2:管理员 3超级管理员
            String role = StpUtil.getSession().get("role").toString();
            String userId = "";
            if ("1".equals(role)) {
                userId=StpUtil.getLoginIdAsString();
            }
            List<AmountInfo> list = baseMapper.selectAllaa(changeType,changeTypes,userId);
            List<AmountInfo> setList = query.setList(PageUtil.getListPage(query.getCurrent(), query.getPageSize(), list), list.size());
            if (!setList.isEmpty()) {
                for (AmountInfo amountInfo : setList) {
                    UserInfo userInfo = userService.view(amountInfo.getUserId()).getData();
                    if (ObjectUtil.isNotEmpty(userInfo)) {
                        if (StrUtil.isEmpty(amountInfo.getPayBank())) {
                            amountInfo.setPayBank(userInfo.getPayBank());
                        }
                        if (StrUtil.isEmpty(amountInfo.getPayCode())) {
                            amountInfo.setPayCode(userInfo.getPayCode());
                        }
                        if (StrUtil.isEmpty(amountInfo.getPayName())) {
                            amountInfo.setPayName(userInfo.getPayName());
                        }
                    }
                }
            }
            query.setList(setList, list.size());
            return CommonResult.success(query);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }


    /**
     * 根据id查看详情
     *
     * @param id
     * @return
     */
    @Override
    public CommonResult<AmountInfo> view(String id) {
        try {
            AmountInfo amountInfo = baseMapper.findById(id);
            return CommonResult.success(amountInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 金额审批
     *
     * @param approvalInfo
     * @return
     */
    @Override
    public CommonResult<AmountInfo> updateAmountApproval(ApprovalInfo approvalInfo) {
        try {
            CommonResult result = approvalInfoService.updateEntity(approvalInfo);
            if (result.getCode() != 0) {
                return result;
            }
            baseMapper.updateUserApproval(approvalInfo.getBusinessId(), approvalInfo.getStatus());
            if ("1".equals(approvalInfo.getStatus())) {
                //审批通过  计算用户余额
                AmountInfo amountInfo = view(approvalInfo.getBusinessId()).getData();
                UserInfo userInfo = userService.view(approvalInfo.getCreator()).getData();
                if (ObjectUtil.isEmpty(userInfo)) {
                    return CommonResult.failed("用户不存在");
                }
                RightInfo rightInfo = rightInfoService.findOne().getData();
                //todo 用户提现金额 * 用户提现手续费比例 = 真正的提现金额
                BigDecimal useAmount = amountInfo.getChangeAmount().multiply(new BigDecimal(rightInfo.getWithdrawalFee()));
                //用户余额 - 提现金额
                BigDecimal newAmount = userInfo.getAmount().subtract(useAmount);
//                amountInfo.setAmount(newAmount);
//                updateEntity(amountInfo);
                userInfo.setAmount(newAmount);
                userService.updateById(userInfo);
            }
            return CommonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }


    /**
     * 新增数据
     *
     * @param amountInfo
     * @return
     */
    @Override
    public CommonResult add(AmountInfo amountInfo) {
        try {
            String userId = amountInfo.getUserId();
            if (StrUtil.isEmpty(userId)) {
                userId = StpUtil.getSession().get("userId").toString();
            }
            UserInfo userInfo = userService.view(userId).getData();
            if (ObjectUtil.isEmpty(userInfo)) {
                return CommonResult.failed("用户不存在");
            }
            amountInfo.setUserId(userId);
            amountInfo.setUserName(userInfo.getUserName());
            if (StrUtil.isNotEmpty(amountInfo.getPayBank()) && StrUtil.isNotEmpty(amountInfo.getPayCode()) && StrUtil.isNotEmpty(amountInfo.getPayName())) {
                if (ObjectUtil.isEmpty(userInfo.getPayBank()) || StrUtil.isEmpty(userInfo.getPayCode()) || StrUtil.isEmpty(userInfo.getPayCode())) {
                    return CommonResult.failed("请先到个人中心，完善收款信息！");
                }
            }
            BigDecimal balance = userInfo.getAmount();
            if (ObjectUtil.isEmpty(balance)) {
                balance = new BigDecimal(0);
            }
            if ("0".equals(amountInfo.getChangeType())) {
                //收入
                balance = balance.add(amountInfo.getChangeAmount());
            } else if ("1".equals(amountInfo.getChangeType())) {
                //支出
                if (balance.compareTo(amountInfo.getChangeAmount()) < 0) {
                    return CommonResult.failed("余额不足");
                }
                balance = balance.subtract(amountInfo.getChangeAmount());
            }
//            if ("2".equals(amountInfo.getChangeType())) {
//                //提现
//                if (balance.compareTo(amountInfo.getChangeAmount()) < 0) {
//                    return CommonResult.failed("余额不足");
//                }
//                amountInfo.setCashStatus("0");
//                //新建审批申请
//                ApprovalInfo approvalInfo = new ApprovalInfo();
//                approvalInfo.setBusinessId(amountInfo.getId());
//                approvalInfo.setBusinessType("1");
//                approvalInfo.setApprover("1");
//                approvalInfo.setApproverName("system");
//                CommonResult result = approvalInfoService.add(approvalInfo);
//                if (result.getCode() != 0) {
//                    return result;
//                }
//            }
            userInfo.setAmount(balance);
            amountInfo.setAmount(balance);
            amountInfo.setId(IdUtil.simpleUUID());
            amountInfo.setCreateTime(DateUtil.now());
            amountInfo.setDelFlag("0");
            baseMapper.insert(amountInfo);

            if ("2".equals(amountInfo.getChangeType())) {
                //提现
                if (balance.compareTo(amountInfo.getChangeAmount()) < 0) {
                    return CommonResult.failed("余额不足");
                }
                amountInfo.setCashStatus("0");
                //新建审批申请
                ApprovalInfo approvalInfo = new ApprovalInfo();
                approvalInfo.setBusinessId(amountInfo.getId());
                approvalInfo.setBusinessType("1");
                approvalInfo.setApprover("1");
                approvalInfo.setApproverName("system");
                CommonResult result = approvalInfoService.add(approvalInfo);
                if (result.getCode() != 0) {
                    return result;
                }
            }
            userService.updateEntityMoney(userInfo);
            return CommonResult.success(amountInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 修改数据
     *
     * @param amountInfo
     * @return
     */
    @Override
    public CommonResult updateEntity(AmountInfo amountInfo) {
        try {
            amountInfo.setUpdateTime(DateUtil.now());
            baseMapper.updateById(amountInfo);
            return CommonResult.success(amountInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 删除数据
     *
     * @param ids
     * @return
     */
    @Override
    public CommonResult delete(List<String> ids) {
        try {
            if (ObjectUtil.isEmpty(ids)) {
                return CommonResult.failed(ResultCodeEnum.PARAM_ERROR);
            }
            for (String id : ids) {
                baseMapper.upDeleteById(id);
            }
            return CommonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

}
